import 'dart:math';

import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:my_app/common/common.dart';
import 'package:my_app/global/global.dart';
import 'package:my_app/qr_detail/qr_detail.dart';
import 'package:my_app/service/api/api.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

///create time : 2019/9/18/018  8:38
///create by : Administrator
///des:刷新组件

class Pulltorefresh extends StatefulWidget {
  @override
  _PulltorefreshState createState() => _PulltorefreshState();
}

class _PulltorefreshState extends State<Pulltorefresh> {
  // button 文字样式
  TextStyle _buttonTextStyle = TextStyle(
    fontSize: 10.0,
    color: Colors.white,
  );
  // button 样式
  ButtonStyle _buttonStyle = TextButton.styleFrom(
    backgroundColor: Color(Common.muji),
    padding: EdgeInsets.all(5),
  );

  DateTime _selectedDate = DateTime.now(); //当前选中的日期
  // TimeOfDay _selectedTime = TimeOfDay.now(); //当前选中的时间
  //label 字体大小
  TextStyle textStyle = TextStyle(fontSize: 10);
  // list 内容文字大小
  TextStyle listStyle = TextStyle(fontSize: 11);
  // label 文字对齐方式
  TextAlign textStyleAlign = TextAlign.end;
  // label 和 input 距离
  Widget widgetWidth = SizedBox(
    width: 10,
  );
  List listData = [];
  double paddingLeft = 45.0;
  double itemWidth = 100.0;
  // listView 滚动
  ScrollController _scrollController = ScrollController();
  String _qrCode = ""; // 二维码
  String _goodsCode = ""; // 商品条码
  String productionDate = ""; // 生产日期
  var _status = 0; // 状态选择值
  String validityDate = ""; // 效期
  String goodsName = ""; // 商品名称
  String startNum = '1'; // 开始数
  String endNum = '10'; // 结束数
  TextEditingController _qrcontroller = new TextEditingController();
  TextEditingController _goodscontroller = new TextEditingController();
  TextEditingController _validityDatecontroller = new TextEditingController();
  TextEditingController _goodNamecontroller = new TextEditingController();
  List<Widget> datas = [];
  List<Widget> models = [];
  RefreshController _controller = RefreshController(initialRefresh: false);
  @override
  initState() {
    getListData("");
    super.initState();
    // Map userinfo = {"userName":"张三","age":20};
  }

  void getListData(status) async {
    var prdDate;
    if (productionDate == "") {
      prdDate = "";
    } else {
      // prdDate = _selectedDate.toString().substring(0, 19);
      prdDate = productionDate;
    }
    if (_status == 0) {
      status = "";
    }
    var data = await ApiService.allQrListData(
      startNum,
      endNum,
      GlobalData.staffID,
      _qrCode,
      _goodsCode,
      validityDate,
      prdDate,
      goodsName,
      status,
    );
    // print(
    //     "_________________________________________listData__________________________");
    // print(data);
    try {
      setState(() {
        datas = models;
      });
      if (data != null) {
        print("qrlistmenu_83");
        print(data);
        if (data.length == 1 && data[0]["ERROR_MSG"] != null) {
          Common.showTost(data.toString());
          return;
        }
        for (int i = 0; i < data.length; i++) {
          if (data[i]["SHELF_LIFE"] == "") {
            data[i]["SHELF_LIFE"] = "效期异常";
          }
          models.add(Item(
              Colors.red,
              data[i]["QR_ID"],
              data[i]["ITEM_ID"],
              data[i]["END_DT"],
              data[i]["SHELF_LIFE"] + data[i]["SHELF_LIFE_UNIT"],
              data[i]["QR_FLG"]));
        }
        listData = data;
        // print("_________________________listData");
        // print(listData);
        setState(() {
          listData = data;
        });
      }
    } catch (err) {
      Future.delayed(Duration(milliseconds: 5000), () {
        Common.showTost(err.toString());
      });
    }
  }

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));
    _controller.refreshCompleted();
  }

  void _onLoading() async {
    await Future.delayed(Duration(milliseconds: 1000));
    startNum = (int.parse(endNum) + 1).toString();
    endNum = (int.parse(endNum) + 10).toString();
    getListData(_status);
    if (mounted) setState(() {});
    _controller.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    Widget _itemBuilder(BuildContext context, int position) {
      return Card(child: this.datas[position]);
    }

    //调起日期选择器
    _showDatePicker() {
      //获取异步方法里面的值的第一种方式：then
      showDatePicker(
        //如下四个参数为必填参数
        context: context,
        initialDate: _selectedDate, //选中的日期
        firstDate: DateTime(1980), //日期选择器上可选择的最早日期
        lastDate: DateTime(2100), //日期选择器上可选择的最晚日期
      ).then((selectedValue) {
        setState(() {
          //将选中的值传递出来
          this._selectedDate = selectedValue!;
          productionDate =
              formatDate(this._selectedDate, [yyyy, "-", mm, "-", "dd"]);
          // this._selectedDate,
          // [HH, ':', nn, ':', ss]);
        });
      });
    }

    return Scaffold(
      appBar: AppBar(
        title: Text('二维码赋码详情'),
        centerTitle: true,
        backgroundColor: Color(Common.muji),
        leading: IconButton(
          tooltip: '返回',
          icon: const Icon(Icons.arrow_back),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ),
      floatingActionButton: FloatingActionButton(
        backgroundColor: Color(Common.muji),
        child: Icon(
          Icons.arrow_upward,
          color: Colors.white,
          size: 40,
        ),
        onPressed: () {
          _scrollController.jumpTo(0.0);
        },
      ),
      body: Column(
        children: [
          SizedBox(
            height: 10,
          ),
          Row(
            children: [
              Container(
                width: 50,
                child: Text(
                  "二维码:",
                  style: textStyle,
                  textAlign: textStyleAlign,
                ),
              ),
              Container(
                height: 30,
                width: 180,
                child: TextField(
                  onChanged: (value) {
                    _qrCode = value;
                    print(value);
                  },
                  controller: _qrcontroller,
                  onSubmitted: (value) {
                    // Uri u = Uri.parse(value);
                    // value = u.queryParameters['qrCode'].toString();
                    if (value.indexOf("=") > -1) {
                      value = value.split("=")[1];
                    }
                    _qrcontroller.text = value;
                    // _qrfocusNode.unfocus();
                    // FocusScope.of(context).requestFocus(_goodsfocusNode);
                    // 保存qr码
                    setState(() {
                      _qrCode = value;
                    });
                  },
                  style: TextStyle(fontSize: 8),
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.black, width: 2.0),
                    ),
                    focusedBorder: Common.focusedBorder,
                  ),
                ),
              ),
              Container(
                width: 50,
                child: Text(
                  "商品条码:",
                  style: textStyle,
                  textAlign: textStyleAlign,
                ),
              ),
              Container(
                height: 30,
                width: 115,
                child: TextField(
                  onChanged: (value) {
                    _goodsCode = value;
                  },
                  controller: _goodscontroller,
                  style: TextStyle(fontSize: 10),
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.black, width: 2.0),
                    ),
                    focusedBorder: Common.focusedBorder,
                  ),
                ),
              ),
              Container(
                width: 50,
                child: Text(
                  "效期:",
                  style: textStyle,
                  textAlign: textStyleAlign,
                ),
              ),
              Container(
                height: 25,
                width: 45,
                child: TextField(
                  onChanged: (value) {
                    validityDate = value;
                    print(value);
                  },
                  // maxLength: 3,
                  keyboardType: TextInputType.number,
                  controller: _validityDatecontroller,
                  style: TextStyle(fontSize: 10),
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.black, width: 2.0),
                    ),
                    focusedBorder: Common.focusedBorder,
                  ),
                ),
              ),
              Container(
                width: 20,
                child: Text(
                  "(天)",
                  style: textStyle,
                  textAlign: TextAlign.start,
                ),
              ),
            ],
          ),
          SizedBox(height: 10),
          Row(
            children: [
              Container(
                width: 50,
                child: Text(
                  "生产日期:",
                  style: textStyle,
                  textAlign: textStyleAlign,
                ),
              ),
              Container(
                height: 30,
                width: 180,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.black38, width: 1),
                  borderRadius: BorderRadius.vertical(
                    top: Radius.elliptical(4, 4),
                    bottom: Radius.elliptical(4, 4),
                  ),
                ),
                child: InkWell(
                  onTap: () => {
                    _showDatePicker(),
                    print(_selectedDate),
                  },
                  child: Row(
                    children: <Widget>[
                      Container(
                        width: 150,
                        child: Text(productionDate),
                      ),

                      // SizedBox(
                      //   width: 110,
                      // ),
                      Icon(
                        Icons.arrow_drop_down,
                      )
                    ],
                  ),
                ),
              ),
              Container(
                width: 50,
                child: Text(
                  "状态:",
                  style: textStyle,
                  textAlign: textStyleAlign,
                ),
              ),
              Container(
                height: 30,
                width: 115,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.black38, width: 1),
                  borderRadius: BorderRadius.vertical(
                    top: Radius.elliptical(4, 4),
                    bottom: Radius.elliptical(4, 4),
                  ),
                ),
                child: DropdownButton(
                    value: _status,
                    icon: Icon(Icons.arrow_drop_down),
                    iconSize: 20,
                    iconEnabledColor: Colors.black.withOpacity(0.7),
                    hint: Text('请选择'),
                    style: TextStyle(color: Colors.black, fontSize: 12),
                    isExpanded: true,
                    underline: Container(color: Colors.white),
                    items: [
                      DropdownMenuItem(
                          child: Row(children: <Widget>[
                            Text('全部 '),
                            SizedBox(width: 10),
                            // Icon(Icons.ac_unit)
                          ]),
                          value: 0),
                      DropdownMenuItem(
                          child: Row(children: <Widget>[
                            Text('已赋码 '),
                            SizedBox(width: 10),
                            // Icon(Icons.ac_unit)
                          ]),
                          value: 1),
                      DropdownMenuItem(
                          child: Row(children: <Widget>[
                            Text('未赋码'),
                            SizedBox(width: 10),
                            // Icon(Icons.ac_unit)
                          ]),
                          value: 2),
                    ],
                    onChanged: (value) {
                      setState(() => _status = value as int);

                      print(value);
                    }),
              ),
              Container(
                width: 50,
                child: Text(
                  "商品名称:",
                  style: textStyle,
                  textAlign: textStyleAlign,
                ),
              ),
              Container(
                height: 30,
                width: 60,
                // color: Colors.amber,
                // decoration: sty(

                // ),
                child: TextField(
                  onChanged: (value) {
                    goodsName = value;
                    print(value);
                  },
                  style: TextStyle(fontSize: 10),
                  controller: _goodNamecontroller,
                  decoration: InputDecoration(
                    border: OutlineInputBorder(
                      borderSide: BorderSide(color: Colors.black, width: 2.0),
                    ),
                    focusedBorder: Common.focusedBorder,
                  ),
                ),
              ),
            ],
          ),
          SizedBox(height: 10),
          Row(
            children: [
              SizedBox(width: 10),
              Container(
                width: 60,
                height: 30,
                child: TextButton(
                  style: _buttonStyle,
                  child: Text(
                    "查询",
                    style: _buttonTextStyle,
                  ),
                  onPressed: () => {
                    if (_status != null)
                      {
                        models = [],
                        getListData(_status.toString()),
                        print('$_qrCode-$_goodsCode-$_status')
                      }
                    else
                      {
                        models = [],
                        getListData(""),
                      }
                  },
                ),
              ),
            ],
          ),
          SizedBox(height: 20),
          Container(
            height: 20,
            child: Row(
              // textBaseline: TextBaseline.ideographic,
              // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              // mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(width: 10),
                Container(
                  width: 210,
                  child: Row(
                    children: [
                      Text(
                        "二维码",
                        style: TextStyle(fontSize: 12),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 85,
                  child: Row(
                    children: [
                      Text(
                        "商品条码",
                        style: TextStyle(fontSize: 12),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 87,
                  child: Row(
                    children: [
                      Text(
                        "到期日期",
                        style: TextStyle(fontSize: 12),
                      ),
                    ],
                  ),
                ),
                Container(
                  width: 86,
                  child: Row(
                    children: [
                      Text(
                        "有效期",
                        style: TextStyle(fontSize: 12),
                      ),
                    ],
                  ),
                ),
                Expanded(
                  flex: 1,
                  child: Text(
                    "状态",
                    style: TextStyle(fontSize: 12),
                  ),
                ),
              ],
            ),
          ),
          Expanded(
            flex: 1,
            child: SmartRefresher(
              enablePullDown: true,
              enablePullUp: true,
              header: WaterDropHeader(),
              footer: ClassicFooter(
                loadStyle: LoadStyle.ShowAlways,
                completeDuration: Duration(microseconds: 50),
              ),
              onRefresh: _onRefresh,
              onLoading: _onLoading,
              controller: _controller,
              child: ListView.builder(
                  controller: _scrollController,
                  itemBuilder: _itemBuilder,
                  itemCount: this.datas.length),
            ),
          )
        ],
      ),
    );
  }

  // Color getRandomColor() {
  //   List<Color> colors = [
  //     Colors.deepOrange,
  //     Colors.amber,
  //     Colors.cyan,
  //     Colors.green,
  //     Colors.red,
  //     Colors.yellow
  //   ];
  //   int randomValue = Random().nextInt(colors.length);
  //   if (randomValue == colors.length) {
  //     randomValue = colors.length - 1;
  //   }
  //   return colors[randomValue];
  // }
}

// class ItemModel {
//   Color _color;
//   IconData _icon;
//   String _mainTitle;
//   String _subTitle;
//   String _des;
//   int _readCount;

//   ItemModel(this._color, this._icon, this._mainTitle, this._subTitle, this._des,
//       this._readCount);

//   int get readCount => _readCount;

//   set readCount(int value) {
//     _readCount = value;
//   }

//   String get des => _des;

//   set des(String value) {
//     _des = value;
//   }

//   String get subTitle => _subTitle;

//   set subTitle(String value) {
//     _subTitle = value;
//   }

//   String get mainTitle => _mainTitle;

//   set mainTitle(String value) {
//     _mainTitle = value;
//   }

//   IconData get icon => _icon;

//   set icon(IconData value) {
//     _icon = value;
//   }

//   Color get color => _color;

//   set color(Color value) {
//     _color = value;
//   }
// }

// class ListData {
//   static List<Widget> getList() {
//     List<Widget> models = [];
//     ItemModel model1 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
//         "俄军大秀战略", "酝酿已久的俄罗斯“中部-2019”战略演习于16日正式启动", 2999);
//     ItemModel model2 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
//         "俄“中部”演习", "俄罗斯卫星网报道称，俄罗斯国防部长绍伊古表示，“中央-2019”战略演习是", 4588);
//     ItemModel model3 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
//         "中国2.7万吨坞登舰", "据印度新德里电视台16日报道，印度海军发现7艘中国军舰在印度洋", 7777);
//     ItemModel model4 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
//         "针对中国？", "美国空军着力打造军用5G网络，5G+VR，飞行员无需上天就能操控战机；美军濒海", 8888);
//     ItemModel model5 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
//         "“凯旋”防空导弹系统", "俄罗斯卫星通讯社报道，俄罗斯北方舰队（Russian Northern Fleet）新闻处", 9999);
//     ItemModel model6 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
//         "火箭军还有骑兵连", "迅速对禁区“敌特分子”活动区域进行侦察定位,战斗小分队", 104754);
//     ItemModel model7 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
//         "侦察兵跨越冰川", "在海拔5000多米的雪域高原，第77集团军某合成旅的侦察兵们正在进行野外驻训", 47545);
//     ItemModel model8 = ItemModel(Colors.red, Icons.airplanemode_active, "军事新闻",
//         "香港被护商船", "新京报快讯 据北海舰队官微消息：“感谢海军!”“祖国万岁!”，当地时", 124574);

//     models.add(Item(model1.color, model1.icon, model1.mainTitle,
//         model1.subTitle, model1.des, model1.readCount));
//     models.add(Item(model2.color, model2.icon, model2.mainTitle,
//         model2.subTitle, model2.des, model2.readCount));
//     models.add(Item(model3.color, model3.icon, model3.mainTitle,
//         model3.subTitle, model3.des, model3.readCount));
//     models.add(Item(model4.color, model4.icon, model4.mainTitle,
//         model4.subTitle, model4.des, model4.readCount));
//     models.add(Item(model5.color, model5.icon, model5.mainTitle,
//         model5.subTitle, model5.des, model5.readCount));
//     models.add(Item(model6.color, model6.icon, model6.mainTitle,
//         model6.subTitle, model6.des, model6.readCount));
//     models.add(Item(model7.color, model7.icon, model7.mainTitle,
//         model7.subTitle, model7.des, model7.readCount));
//     models.add(Item(model8.color, model8.icon, model8.mainTitle,
//         model8.subTitle, model8.des, model8.readCount));
//     return models;
//   }
// }

class Item extends StatelessWidget {
  Color color;
  String qrCode;
  String goodsCode;
  String endDate;
  String shelflife;
  String status;
  Item(this.color, this.qrCode, this.goodsCode, this.endDate, this.shelflife,
      this.status);
  // list 内容文字大小
  TextStyle listStyle = TextStyle(fontSize: 11);
  @override
  Widget build(BuildContext context) {
    return Container(
      height: 40,
      child: InkWell(
        onTap: () {
          print(qrCode);
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return QrDetail(
              qrCode: qrCode,
              isEdit: status,
            );
          })).then((value) => {
                print(value),
                // _qrcontroller.text = "",
                // _goodscontroller.text = "",
                // _validityDatecontroller.text = "",
                // _goodNamecontroller.text = "",
                // setState(() {
                //   productionDate = "";
                //   _qrCode = "";
                //   goodsName = "";
                //   _goodsCode = "";
                //   _status = 0;
                // }),
                // getListData(''),
              });
        },
        child: Row(
          // textBaseline: TextBaseline.ideographic,
          // mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Container(
              width: 210,
              child: Container(
                height: 14,
                // decoration: BoxDecoration(
                //   border: Border(
                //     bottom: BorderSide(width: 0.3, color: Colors.black),
                //   ),
                // ),
                child: Text(
                  qrCode,
                  style: listStyle,
                ),
              ),
            ),
            Container(
              width: 85,
              child: Container(
                height: 14,
                // decoration: BoxDecoration(
                //   border: Border(
                //     bottom: BorderSide(width: 0.3, color: Colors.black),
                //   ),
                // ),
                child: Text(
                  goodsCode,
                  // "4556777089363",
                  style: listStyle,
                ),
              ),
            ),
            Container(
              width: 87,
              child: Container(
                height: 14,
                // decoration: BoxDecoration(
                //   border: Border(
                //     bottom: BorderSide(width: 0.3, color: Colors.black),
                //   ),
                // ),
                child: Text(
                  endDate,
                  // "2022-12-30",
                  style: listStyle,
                ),
              ),
            ),
            Container(
              width: 87,
              child: Container(
                height: 14,
                // decoration: BoxDecoration(
                //   border: Border(
                //     bottom: BorderSide(width: 0.3, color: Colors.black),
                //   ),
                // ),
                width: 100,
                child: Text(
                  shelflife,
                  // "2022-12-30",
                  style: listStyle,
                ),
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                height: 14,
                // decoration: BoxDecoration(
                //   border: Border(
                //     bottom: BorderSide(width: 0.3, color: Colors.black),
                //   ),
                // ),
                child: Text(
                  status,
                  style: listStyle,
                ),
              ),
            ),
            SizedBox(width: 10),
            // Text("______"),
            // Text(this.listData[i]["goodsCode"]),
          ],
        ),
      ),
    );

    // Container(
    //   margin: EdgeInsets.fromLTRB(10.0, 5.0, 10.0, 5.0),
    //   height: 90.0,
    //   child: Row(
    //     children: <Widget>[
    //       Container(
    //         width: 90.0,
    //         color: color,
    //         alignment: Alignment.center,
    //         child: Icon(icon, color: Colors.white),
    //       ),
    //       SizedBox(width: 10),
    //       Expanded(
    //           child: Column(
    //         crossAxisAlignment: CrossAxisAlignment.start,
    //         children: <Widget>[
    //           Expanded(
    //               child: Text(mainTitle,
    //                   style: TextStyle(
    //                       fontWeight: FontWeight.bold, fontSize: 18.0))),
    //           Expanded(child: Text(subTitle, style: TextStyle(fontSize: 14.0))),
    //           Expanded(
    //               child: Text(
    //             des,
    //             style: TextStyle(fontSize: 13.0),
    //             overflow: TextOverflow.ellipsis,
    //           )),
    //           Expanded(
    //               child: Text("阅读量:${readCount.toString()}",
    //                   style: TextStyle(
    //                       fontWeight: FontWeight.bold,
    //                       fontSize: 14.0,
    //                       color: Colors.redAccent))),
    //         ],
    //       ))
    //     ],
    //   ),
    // );
  }
}
